package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.service.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: itheima
 * @create: 2022-03-28 14:07
 */
@Component
@Slf4j
public class ArticleTask {

    //注意：freemarker.template包下的
    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    @Lazy
    private IApArticleService articleService;

    /**
     * 创建某一篇文章对应html文件；将html文件上传到Minio分布式存储服务；更新文章静态页字段
     *
     * @param apArticleContent 文章内容
     */
    @Async("leadnewsExecutor")
    public void createArticleHtml(ApArticleContent apArticleContent, ApArticle apArticle) {
        try {
            //1.基于Freemarker生成静态html
            //1.1 加载模板文件 路径默认templates/article.ftl
            Template template = configuration.getTemplate("article.ftl");
            //1.2 定义数据模型
            Map<String, Object> dataModel = new HashMap<>();
            //1.3 模板文件中需要内容 内容由多个段落构成
            dataModel.put("content", JSON.parseArray(apArticleContent.getContent()));

            //1.3 使用模板引擎对象将模板跟数据进行合并 产生静态页文件/文件流
            StringWriter writer = new StringWriter();
            template.process(dataModel, writer);

            //2.将生成的静态页文件上传到MinIO中
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String staticUrl = minIOService.upload(apArticle.getId() + ".html", inputStream, "text/html");

            //3.将得到到上传后的静态页url地址。更新文章表静态页字段
            apArticle.setStaticUrl(staticUrl);
            articleService.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
